package util

import (
	"context"
	"errors"
	"fmt"
	"gitee.com/go-mid/infra/xlog"
	"time"
)

//分布式锁代码段
//降级了的分布式锁。如果缓存挂掉了，则放弃分布式锁失效
//todo 空实现
func DistributeLockExec(ctx context.Context, lockKey string, expiration, timeout time.Duration, exec func() error) error {
	fun := "DistributeLockExec -->"
	lockVal := fmt.Sprintf("%d", time.Now().Nanosecond())
	defer func() {
		//r, err := RedisClient.Unlock(ctx, lockKey, lockVal)
		//if err != nil {
		//	xlog.Errorf(ctx, "%s  unlock error: lockKey: %s, lockVal: %s, err: %v ", fun, lockKey, lockVal, err)
		//}
		//if !r {
		//	xlog.Errorf(ctx, "%s  unlock fail: lockKey: %s, lockVal: %s ", fun, lockKey, lockVal)
		//}
	}()
	var r = true
	//r, err := RedisClient.LockWithTimeout(ctx, lockKey, lockVal, expiration, timeout)
	//if err != nil {
	//	xlog.Errorf(ctx, "%s lock error: lockKey: %s, lockVal: %s, err: %v ", fun, lockKey, lockVal, err)
	//	return exec()
	//}
	if r {
		return exec()
	}
	xlog.Errorf(ctx, "%s lock fail: lockKey: %s, lockVal: %s ", fun, lockKey, lockVal)
	return errors.New("lock fail: " + lockKey)
}
